package com.jjmmbb.anydolist;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;

import com.jjmmbb.db.db.ItemDao;
import com.jjmmbb.db.db.ItemManager;
import com.jjmmbb.db.pojo.Enums;
import com.jjmmbb.db.pojo.Item;
import com.jjmmbb.dolist.ex.ScreenObserver;
import com.jjmmbb.dolist.ex.ScreenObserver.ScreenStateListener;

public class DoListService extends Service {

	long ChekFrequency = 10000;
	long strikeLastDay = -1;
	long strikeLastHour = -1;

	private ScreenObserver mScreenObserver;
	private WifiManager wifiManager;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	// 当启动Service的时候会调用这个方法
	@Override
	public void onCreate() {
		System.out.println("onCreate");
		// 计时器实现
		Message message = handler.obtainMessage(1);
		handler.sendMessageDelayed(message, ChekFrequency); // 发送message
		super.onCreate();
	}

	// 当系统被销毁的时候会调用这个方法
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	// 当启动Service的时候会调用这个方法
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		System.out.println("onStartCommand");

		// notify2();
		// 监控屏幕
		ObserverScreen();
		return super.onStartCommand(intent, flags, startId);
	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) { // handle message
			switch (msg.what) {
			case 1:
				notify2();// UI操作

				Message message = handler.obtainMessage(1);
				// 发送message , 这样消息就能循环发送
				handler.sendMessageDelayed(message, ChekFrequency);
			}
			super.handleMessage(msg);
		}
	};

	ItemManager im;

	// 将被定时调用,先获取配置文件,判断是否需要发出通知栏提醒
	void notify2() {
		nofity1();// 整点报时

		notify3();// 通知栏提醒
	}

	private void nofity1() {
		Calendar c = Calendar.getInstance();
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		// 保证不出现重复报时
		if (strikeLastDay == day && strikeLastHour == hour) {
			return;
		}

		if (c.get(Calendar.MINUTE) == 0 && c.get(Calendar.SECOND) <= 10) {
			int strike = Util.getPreferenceStrike(this);
			ArrayList<Integer> list = Util.MarkDecodeByBinary(strike);
			if (hour == 0) {
				hour = 24;
			}
			for (int i : list) {
				if (i == hour) {
					strikeLastDay = day;
					strikeLastHour = hour;
					strikeHour(i);
					break;
				}
			}
		}
	}

	private void strikeHour(int hour) {
		int rexIndex = R.raw.c00;
		switch (hour) {
		case 1:
			rexIndex = R.raw.c01;
			break;
		case 2:
			rexIndex = R.raw.c02;
			break;
		case 3:
			rexIndex = R.raw.c03;
			break;
		case 4:
			rexIndex = R.raw.c04;
			break;
		case 5:
			rexIndex = R.raw.c05;
			break;
		case 6:
			rexIndex = R.raw.c06;
			break;
		case 7:
			rexIndex = R.raw.c07;
			break;
		case 8:
			rexIndex = R.raw.c08;
			break;
		case 9:
			rexIndex = R.raw.c09;
			break;
		case 10:
			rexIndex = R.raw.c10;
			break;
		case 11:
			rexIndex = R.raw.c11;
			break;
		case 12:
			rexIndex = R.raw.c12;
			break;
		case 13:
			rexIndex = R.raw.c13;
			break;
		case 14:
			rexIndex = R.raw.c14;
			break;
		case 15:
			rexIndex = R.raw.c15;
			break;
		case 16:
			rexIndex = R.raw.c16;
			break;
		case 17:
			rexIndex = R.raw.c17;
			break;
		case 18:
			rexIndex = R.raw.c18;
			break;
		case 19:
			rexIndex = R.raw.c19;
			break;
		case 20:
			rexIndex = R.raw.c20;
			break;
		case 21:
			rexIndex = R.raw.c21;
			break;
		case 22:
			rexIndex = R.raw.c22;
			break;
		case 23:
			rexIndex = R.raw.c23;
			break;
		case 24:
			rexIndex = R.raw.c00;
			break;
		default:
			break;
		}
		MediaPlayer sound = MediaPlayer.create(this, rexIndex);
		sound.start();
	}

	private void ObserverScreen() {
		wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
		mScreenObserver = new ScreenObserver(this);
		mScreenObserver.requestScreenStateUpdate(new ScreenStateListener() {
			@Override
			public void onScreenOn() {
				doSomethingOnScreenOn();
			}

			@Override
			public void onScreenOff() {
				doSomethingOnScreenOff();
			}
		});
	}

	private void doSomethingOnScreenOn() {
		System.out.println("Screen is on");
		if (Comm.autoWIFI) {
			wifiManager.setWifiEnabled(true);
		}
	}

	private void doSomethingOnScreenOff() {
		System.out.println("Screen is off");
		if (Comm.autoWIFI) {
			wifiManager.setWifiEnabled(false);
		}
	}

	// ***************************************************************

	private void notify3() {
		// 更新配置文件
		if (null == im) {
			im = new ItemManager(this);
		}
		Long now = new Date().getTime();
		String sql = "select * from "
				+ ItemDao.tableName
				+ " where type=0 and typeAlarm>-5 and typeAlarm!=0 and timeAlarm<"
				+ now + " order by timeAlarm asc";

		ArrayList<Item> list = im.getListAsSQL(sql);// 获取需要提醒的记事项

		if (null != list && list.size() > 0) {
			Item item = list.get(0);
			String title = item.title;
			long time = item.timeAlarm;
			System.out.println(title + "  " + time + " " + item.typeAlarm);
			showNotify(title, time);// 显示通知栏消息
			saveAlarmItemIdToPreferences(item.id);// 保存最后提醒的itemid
			if (item.typeAlarm == Enums.Alarm_Once) {
				item.typeAlarm = Enums.Alarm_No;
				item.update(im);
			} else if (item.typeAlarm == Enums.Alarm_Daily) {
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(item.timeAlarm);
				cal.add(Calendar.DAY_OF_MONTH, 1);
				item.timeAlarm = cal.getTimeInMillis();
				item.update(im);
			} else {
				ArrayList<Integer> listAlarm = Util
						.MarkDecodeByBinary(item.typeAlarm);
				Calendar cal = Calendar.getInstance();
				cal.setTimeInMillis(item.timeAlarm);
				if (listAlarm != null && listAlarm.size() > 0) {
					for (int i = 1; i <= 7; i++) {
						cal.add(Calendar.DAY_OF_MONTH, 1);
						if (listAlarm.contains(getWeekOfDate(cal))) {
							System.out.println(i);
							item.timeAlarm = cal.getTimeInMillis();
							item.update(im);
							break;
						}
					}
				} else {
					item.typeAlarm = Enums.Alarm_No;
					item.update(im);
				}
			}
		}
		// for (Item item : list) {
		// try {
		// title = item.title;
		// System.out.println(title + "  " + item.timeAlarm);
		// } catch (Exception e) {
		// }
		// }

		// Long timeAlarm = Long.MAX_VALUE;
		// String alarmList = getConfigFromPreferences();
		// System.out.println(alarmList);
		// if (alarmList.length() < 5) {
		// stopSelf();
		// return;
		// }
		// try {
		// JSONObject obj = new JSONObject(alarmList);
		// Iterator keys = obj.keys();
		//
		// // 循环json字符串,获取最小时间那个
		// while (keys.hasNext()) {
		// String tempTitle = (String) keys.next();
		// Long tempTime = obj.getLong(tempTitle);
		// if (timeAlarm > tempTime) {
		// title = tempTitle;
		// timeAlarm = tempTime;
		// }
		// }
		// if (timeAlarm <= new Date().getTime()) {
		// showNotify(title, timeAlarm);// 显示通知栏消息
		// obj.remove(title);// 移除已经发出的通知
		// saveAlarmList2Preferences(obj.toString());// 保存剩下的配置文件
		// }
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
	}

	// 消息通知栏
	// msg:消息标题 = item.title, timeAlarm:原的提醒时间=item.timeAlarm,
	void showNotify(String msg, Long timeAlarm) {
		// 定义NotificationManager
		String ns = Context.NOTIFICATION_SERVICE;

		// 定义通知栏展现的内容信息
		int icon = R.drawable.logo;
		String appName = getString(R.string.app_name);
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, msg, when);

		// 定义下拉通知栏时要展现的内容信息
		Context context = getApplicationContext();
		CharSequence contentTitle = msg;
		CharSequence contentText = appName;
		Intent intent = new Intent(this, ItemEditActivity.class);
		// Bundle bundle = new Bundle();
		// bundle.putLong("timeAlarm", timeAlarm);
		// intent.putExtras(bundle);
		// intent.putExtra("timeAlarm", timeAlarm);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
				intent, 0);
		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);

		// 添加声音提示
		notification.defaults = Notification.DEFAULT_SOUND;
		// audioStreamType的值必须AudioManager中的值，代表着响铃的模式
		notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;

		// 下边的两个方式可以添加音乐
		// notification.sound =
		// Uri.parse("file:///sdcard/notification/ringer.mp3");
		// notification.sound =
		// Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");

		// 用NotificationManager的notify方法通知用户生成标题栏消息通知
		NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
		notificationManager.notify(android.R.id.icon, notification);
	}

	// 保存提醒配置
	private void saveAlarmItemIdToPreferences(int id) {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = settings.edit(); // 取得编辑对象
		editor.putInt("AlarmItemId", id);
		editor.commit();// 提交保存
	}

	// 从sharedpareferences获取配置信息
	private String getConfigFromPreferences() {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		return settings.getString("AlarmList", "");// 这是一个json数组
	}

	// 保存提醒配置
	private void saveAlarmList2Preferences(String jsonStr) {
		SharedPreferences settings = PreferenceManager
				.getDefaultSharedPreferences(this);
		SharedPreferences.Editor editor = settings.edit(); // 取得编辑对象
		editor.putString("AlarmList", jsonStr);// 添加值
		editor.commit();// 提交保存
	}

	private int getWeekOfDate(Calendar cal) {
		int[] weekDays = { 7, 1, 2, 3, 4, 5, 6 };
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		return weekDays[w];
	}
}